/*
 * File: findTrip.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package triperest.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import triperest.Destination;
import triperest.Trip;
import triperest.TriperestUser;

/**
 * The Class findTrip.
 */
public class findTrip extends HttpServlet
{

    /*
     * (non-Javadoc)
     * 
     * @see
     * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
     * , javax.servlet.http.HttpServletResponse)
     */
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException
    {

        resp.setContentType("text/plain");
        ArrayList<Trip> trips = Trip.findTrips(req.getParameter("q"));

        try
        {
            JSONArray retVal = new JSONArray();
            Iterator<Trip> i = trips.iterator();
            while (i.hasNext())
            {
                Trip trip = i.next();
                JSONObject JsonTrip = new JSONObject();
                JsonTrip.put("name", trip.getName());
                JsonTrip.put("description", trip.getDescription());
                JsonTrip.put("mine", trip.isThisMine(new TriperestUser(req)));
                JSONArray destinations = new JSONArray();
                ArrayList<Destination> dests = trip.getDestinations();
                for (int j = 0; j < dests.size(); j++)
                {
                    destinations.put(new JSONObject().put("id",
                            dests.get(j).getID()).put("name",
                            dests.get(j).getName()));
                }
                JsonTrip.put("destinations", destinations);
                retVal.put(JsonTrip);
            }
            resp.getWriter().append(retVal.toString());
        } catch (JSONException e)
        {
            // Do Nothing
        }

    }
}
